package com.dzm.xgb.core.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.dzm.xgb.core.pojo.dto.ExcelDictDTO;
import com.dzm.xgb.core.pojo.entity.Dict;
import com.dzm.xgb.core.service.DictService;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 作者：Dzm
 * 时间：2024-08-28-15:08
 * 功能：
 */

public class MyReadListener extends AnalysisEventListener<ExcelDictDTO> {

    private static int BATCH_SIZE = 10; //每次最多读10条
    private List<ExcelDictDTO> dtos = new ArrayList<>();
    private DictService dictService;

    public MyReadListener(DictService dictService) {
        this.dictService = dictService;
    }

    //每读一行执行一次
    @Override
    public void invoke(ExcelDictDTO dto, AnalysisContext analysisContext) {
        dtos.add(dto);
        //达到10条加一次
        if(dtos.size() > BATCH_SIZE) {
            save(dtos);
            dtos.clear();
        }
    }

    //读取完后的回调
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        //将剩余内容读取
        save(dtos);
    }

    private void save(List<ExcelDictDTO> dtos) {
        List<Dict> collect = dtos.stream().map(obj -> {
            Dict dict = new Dict();
            BeanUtils.copyProperties(obj, dict);
            return dict;
        }).collect(Collectors.toList());

        dictService.saveBatch(collect);
    }
}
